package com.ktwlsoft.archivemanage.service.security;

import com.ktwlsoft.archivemanage.domain.business.businessService.SecurityRoleService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.ActionSource;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;

/**aop*/
@Component
@Aspect
public class AuthorisizeIntercepter {

    private final SecurityRoleService securityRoleService;

    public AuthorisizeIntercepter(SecurityRoleService securityRoleService) {
        this.securityRoleService = securityRoleService;
    }

    @Pointcut("execution(* com.ktwlsoft.archivemanage.controller..*.*(..))")
    private void authenticateMethods() {
    }

    @Around("authenticateMethods()")
    private ResponseEntity<?> methodAuthenticate(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Annotation userAuthenticateAnnotation = method.getAnnotation(UserAuthenticate.class);
        if (userAuthenticateAnnotation != null) {
            UserAuthenticate userAuthenticate = (UserAuthenticate) userAuthenticateAnnotation;
            if (userAuthenticate.skip()) {
                return (ResponseEntity<?>) joinPoint.proceed();
            }
            String actionCode = userAuthenticate.actionCode();
            Account currentUser = UserPrincipal.getCurrentUser();
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Result.body(null, ResultType.CHECK_ERROR).withMessage("未获取到当前用户，请先登录"));
            }
            List<String> userActions = securityRoleService.findActionCodesByUserName(currentUser.getUserName());
            if (!userActions.contains(actionCode)) {
                return ResponseEntity.status(401).body(Result.body(null, ResultType.CHECK_ERROR).withMessage("当前用户没有访问权限"));
            }
        }
        return (ResponseEntity<?>) joinPoint.proceed();
    }
}
